package com.yjd.bi.etl.funds.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.yjd.bi.etl.comm.BaseService;
import com.yjd.bi.etl.comm.Constants;
import com.yjd.bi.etl.sql.FundsSqlConstants;
import com.yjd.bi.etl.sql.UserSqlConstants;
import com.yjd.bi.report.model.BiDatabaseInfoModel;
import com.yjd.bi.report.util.BiUtil;
import com.yjd.comm.util.ArithUtil;
import com.yjd.comm.util.DateUtil;
import com.yjd.comm.util.FrameUtil;

@Component("fundsStatisticsService")
public class FundsStatisticsService extends BaseService {

	private static int comitNum = 1; // 提交的数量

	private static Long interval_1 = 86400L; // 每天的时间间隔

	private static Long interval_2 = 86399L;// 每天的时间间隔

	private static Long interval_3 = 1800L;// 每30分钟的时间间隔

	private static Long interval_4 = 1799L;// 每30分钟的时间间隔
		

	public void everyDayStatisticsFunds() throws Exception {
		Long statisticsBegin = FrameUtil.getTime();
		BiDatabaseInfoModel model = this.getBiDatabaseInfoModel();
		JdbcTemplate jt = BiUtil.getJdbcTemplate(model);
		Long beginTime = 0l; // 初始化开始时间
		Long ends = Long.parseLong(DateUtil.timestampToDateString(
				FrameUtil.getTime(null), DateUtil.PATTERN_yyyyMMdd));
		Long overTime = DateUtil.getTimestampToTimestamp(
				FrameUtil.getTime(null), DateUtil.PATTERN_yyyy_MM_dd);
		int rows = 0;
		Double availablePrice = 0d;
		Double allAvailablePrice = 0d;
		
		//每次统计清空前30天数据，重新跑
		jt.update(FundsSqlConstants.DELETE_FUNDS_STATISTIC);
		
		List res = jt.queryForList(FundsSqlConstants.FUNDSSTATISTICS_MAXDATE);
		
		if (res != null && res.size()>0  ) {
			String maxDate = String.valueOf(((Map)res.get(0)).get("maxDate"));
			beginTime = DateUtil.dateStringToTimestamp(maxDate,
					DateUtil.PATTERN_yyyyMMdd);
			availablePrice = Double.parseDouble(String.valueOf(((Map)res.get(0)).get("available")));
			
		} else {
			beginTime = Constants.INITIALIZATION_TIME;
		}

		List<Object[]> insertList = new ArrayList<Object[]>();
		List<Object[]> updateList = new ArrayList<Object[]>();
		Object[] queryParam;
	 

		do {

			Long startTime = beginTime + interval_1;
			Long endTime = startTime + interval_2;
			Long staticsDate = Long.parseLong(DateUtil.timestampToDateString(
					startTime, DateUtil.PATTERN_yyyyMMdd));
			if (staticsDate < ends) {

				queryParam = new Object[] { startTime, endTime };

				Double investPrice = 0d, creditorPrice = 0d, walProjectPrice = 0d, sumPrice = 0d, rechargePrice = 0d,rechargeWalPrice = 0d, cashPrice = 0d, 
						 borrowPrice = 0d,addPrice = 0d,subPrice = 0d,changePrice =0d,freezePrice=0d,thawPrice=0d,lck_available= 0d,cashDepoPrice=0d;
				// 成交量统计
				investPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.INVEST_SUMPRICE_SQL,
								queryParam).get("sumPrice").toString());
				creditorPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.CREDITOR_SUMPRICE_SQL,
								queryParam).get("sumPrice").toString());
				/*walProjectPrice = Double.parseDouble(jt
						.queryForMap(
								FundsSqlConstants.WAL_PROJECT_SUMPRICE_SQL,
								queryParam).get("sumPrice").toString());*/
				sumPrice = ArithUtil.adds(investPrice, creditorPrice);

				// 充值金额统计
				rechargePrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.RECHARGE_SUMPRICE_SQL,
								queryParam).get("recharge").toString());
				
				lck_available = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.LCK_AVAILABLE,
								new Object[] {  endTime }).get("available").toString());
				
				/*// 充值金额统计（小钱包）
				rechargeWalPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.RECHARGE_SUMPRICE_WAL_SQL,
								queryParam).get("recharge").toString());*/
				
				// 提现金额统计
				cashPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.CASH_SUMPRICE_SQL,
								queryParam).get("cash").toString());
				
				cashDepoPrice=Double.parseDouble(jt.queryForMap(FundsSqlConstants.CASH_DEPO_SUMPRICE_SQL,
								queryParam).get("cash").toString());

/*					// 可用余额统计
					addPrice = Double.parseDouble(jt
							.queryForMap(FundsSqlConstants.ADD_AVAILABLE_SUMPRICE_SQL,
									queryParam).get("available").toString());
					
					subPrice = Double.parseDouble(jt
							.queryForMap(FundsSqlConstants.SUB_AVAILABLE_SUMPRICE_SQL,
									queryParam).get("available").toString());
					thawPrice = Double.parseDouble(jt
							.queryForMap(FundsSqlConstants.ADD_AVAILABLE_SUMPRICE_SQL_JD,
									queryParam).get("available").toString());
					
					freezePrice = Double.parseDouble(jt
							.queryForMap(FundsSqlConstants.ADD_AVAILABLE_SUMPRICE_SQL_DJ,
									queryParam).get("available").toString());
					
					changePrice = ArithUtil.sub(ArithUtil.add(addPrice, thawPrice), ArithUtil.add(subPrice,freezePrice));
					
					availablePrice = ArithUtil.add(availablePrice, changePrice);*/
					
				  queryParam = new Object[] {endTime};
				 /* availablePrice = Double.parseDouble(jt
							.queryForMap(FundsSqlConstants.AVAILABLE_SUMPRICE_SQL,
									queryParam).get("available").toString());

				allAvailablePrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.AVAILABLE_SUMPRICE_SQL_ALL,
								queryParam).get("available").toString());*/
		

				queryParam = new Object[] {  endTime ,startTime};
				// 借款统计
				Object bp=jt
						.queryForMap(FundsSqlConstants.BORROW_SUMPRICE_SQL,
								new Object[] {  endTime}).get("borrow");
				borrowPrice = Double.parseDouble(bp==null?"0.0":bp.toString());

				queryParam = new Object[] { staticsDate };
				List<Long> idList = jt.queryForList(FundsSqlConstants.EXIST_FUNDSSTATISTICS, Long.class, queryParam);
				//List idList = jt.queryForList(
				//		FundsSqlConstants.EXIST_FUNDSSTATISTICS, queryParam);

				if (idList == null || idList.size() == 0) {
					queryParam = new Object[] { sumPrice, rechargePrice,
							cashPrice, availablePrice, borrowPrice, staticsDate,thawPrice,freezePrice,subPrice, addPrice,lck_available,allAvailablePrice,cashDepoPrice };
					insertList.add(queryParam);
				} else {
					Long id = Long.parseLong(idList.get(0).toString());
					queryParam = new Object[] { sumPrice, ArithUtil.add(rechargePrice,rechargeWalPrice),
							cashPrice, availablePrice, borrowPrice,thawPrice,freezePrice,subPrice, addPrice,lck_available,allAvailablePrice,cashDepoPrice, id };
					updateList.add(queryParam);
				}

				if (insertList.size() == comitNum) {
					batchUpdateData(model,
							FundsSqlConstants.INSERT_FUNDSSTATISTICS_SQL,
							insertList);
					insertList = new ArrayList<Object[]>();
					rows = rows + comitNum;

				}

				if (updateList.size() == comitNum) {
					batchUpdateData(model,
							FundsSqlConstants.UPDATE_FUNDSSTATISTICS_SQL,
							updateList);
					insertList = new ArrayList<Object[]>();
					rows = rows + comitNum;
				}

			}
			beginTime = beginTime + interval_1;

		} while (beginTime < overTime);

		if (insertList.size() > 0) {
			rows = rows
					+ batchUpdateData(model,
							FundsSqlConstants.INSERT_FUNDSSTATISTICS_SQL,
							insertList);

		}

		if (updateList.size() > 0) {
			rows = rows
					+ batchUpdateData(model,
							FundsSqlConstants.UPDATE_FUNDSSTATISTICS_SQL,
							updateList);
		}

		Long statisticsEnd = FrameUtil.getTime();
		Long times = statisticsEnd - statisticsBegin;
		logger.info("资金量统计（每日）本次运行数据开始时间："
				+ DateUtil.formatTimeToStr(beginTime,
						DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss)
				+ "结束时间："
				+ DateUtil.formatTimeToStr(overTime,
						DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss)
				+ "共运行记录数："
				+ rows
				+ "执行开始时间："
				+ DateUtil.formatTimeToStr(statisticsBegin,
						DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss)
				+ "执行结束时间:"
				+ DateUtil.formatTimeToStr(statisticsEnd,
						DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss) + "共花费时间："
				+ times);
	}

	public void every30MinuteStatisticsFunds() throws Exception {
		Long statisticsBegin = FrameUtil.getTime();
		BiDatabaseInfoModel model = this.getBiDatabaseInfoModel();
		JdbcTemplate jt = BiUtil.getJdbcTemplate(model);
		Long beginTime = 0l; // 初始化开始时间
		Long ends = Long.parseLong(DateUtil.timestampToDateString(
				FrameUtil.getTime(null), DateUtil.PATTERN_yyyyMMddHHmmss));
		Long overTime = DateUtil.getTimestampToTimestamp(
				FrameUtil.getTime(null), DateUtil.PATTERN_yyyyMMddHHmmss);
		int rows = 0;
		Double availablePrice = 0d;

		List res = jt.queryForList(FundsSqlConstants.FUNDSSTATISTICS_MINUTE_MAXDATE);
		
		if (res != null && res.size()>0) {
			String maxDate = String.valueOf(((Map)res.get(0)).get("maxDate"));
			beginTime = DateUtil.dateStringToTimestamp(maxDate,
					DateUtil.PATTERN_yyyyMMddHHmmss);
			
			availablePrice = Double.parseDouble(String.valueOf(((Map)res.get(0)).get("available")));
			
		} else {
			beginTime = Constants.INITIALIZATION_TIME;
		}

		List<Object[]> insertList = new ArrayList<Object[]>();
		List<Object[]> updateList = new ArrayList<Object[]>();
		Object[] queryParam; 

		
		do {

			Long startTime = beginTime + interval_3;
			Long endTime = startTime + interval_4;
			Long staticsDate = Long.parseLong(DateUtil.timestampToDateString(
					startTime, DateUtil.PATTERN_yyyyMMddHHmmss));
			if (staticsDate < ends) {

				queryParam = new Object[] { startTime, endTime };

				Double investPrice = 0d, creditorPrice = 0d, walProjectPrice = 0d, sumPrice = 0d, rechargePrice = 0d,rechargeWalPrice = 0d,cashPrice = 0d, 
						borrowPrice = 0d,addPrice = 0d,subPrice = 0d,changePrice =0d,thawPrice=0d,freezePrice=0d;
				// 成交量统计
				investPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.INVEST_SUMPRICE_SQL,
								queryParam).get("sumPrice").toString());
				creditorPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.CREDITOR_SUMPRICE_SQL,
								queryParam).get("sumPrice").toString());
				walProjectPrice = Double.parseDouble(jt
						.queryForMap(
								FundsSqlConstants.WAL_PROJECT_SUMPRICE_SQL,
								queryParam).get("sumPrice").toString());
				sumPrice = ArithUtil.adds(investPrice, creditorPrice,
						walProjectPrice);

				// 充值金额统计
				rechargePrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.RECHARGE_SUMPRICE_SQL,
								queryParam).get("recharge").toString());
				
				// 充值金额统计（小钱包）
				rechargeWalPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.RECHARGE_SUMPRICE_WAL_SQL,
								queryParam).get("recharge").toString());
				
				// 提现金额统计
				cashPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.CASH_SUMPRICE_SQL,
								queryParam).get("cash").toString());

				// 可用余额统计
				addPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.ADD_AVAILABLE_SUMPRICE_SQL,
								queryParam).get("available").toString());
				
				subPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.SUB_AVAILABLE_SUMPRICE_SQL,
								queryParam).get("available").toString());
                
				thawPrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.ADD_AVAILABLE_SUMPRICE_SQL_JD,
								queryParam).get("available").toString());
				
				freezePrice = Double.parseDouble(jt
						.queryForMap(FundsSqlConstants.ADD_AVAILABLE_SUMPRICE_SQL_DJ,
								queryParam).get("available").toString());
				
				changePrice = ArithUtil.sub(ArithUtil.add(addPrice, thawPrice), ArithUtil.add(subPrice,freezePrice));
				
				availablePrice = ArithUtil.add(availablePrice, changePrice);
				
				queryParam = new Object[] {  endTime ,startTime};
				// 借款统计
//				borrowPrice = Double.parseDouble(jt
//						.queryForMap(FundsSqlConstants.BORROW_SUMPRICE_SQL,
//								queryParam).get("borrow").toString());

				queryParam = new Object[] { staticsDate };
				List<Long> idList = jt.queryForList(FundsSqlConstants.EXIST_FUNDSSTATISTICS_MINUTE, Long.class, queryParam);
				//List idList = jt.queryForList(
				//		FundsSqlConstants.EXIST_FUNDSSTATISTICS_MINUTE,
				//		queryParam);

				if (idList == null || idList.size() == 0) {
					queryParam = new Object[] { sumPrice, ArithUtil.add(rechargePrice,rechargeWalPrice),
							cashPrice, availablePrice, borrowPrice, staticsDate,thawPrice,freezePrice,subPrice, addPrice};
					insertList.add(queryParam);
				} else {
					Long id = Long.parseLong(idList.get(0).toString());
					queryParam = new Object[] { sumPrice, ArithUtil.add(rechargePrice,rechargeWalPrice),
							cashPrice, availablePrice, borrowPrice,thawPrice,freezePrice,subPrice, addPrice, id };
					updateList.add(queryParam);
				}
			}

			if (insertList.size() == comitNum) {
				batchUpdateData(model,
						FundsSqlConstants.INSERT_FUNDSSTATISTICS_MINUTE_SQL,
						insertList);
				insertList = new ArrayList<Object[]>();
				rows = rows + comitNum;

			}

			if (updateList.size() == comitNum) {
				batchUpdateData(model,
						FundsSqlConstants.UPDATE_FUNDSSTATISTICS_MINUTE_SQL,
						updateList);
				insertList = new ArrayList<Object[]>();
				rows = rows + comitNum;
			}

			beginTime = beginTime + interval_3;

		} while (beginTime < overTime);

		if (insertList.size() > 0) {
			rows = rows
					+ batchUpdateData(
							model,
							FundsSqlConstants.INSERT_FUNDSSTATISTICS_MINUTE_SQL,
							insertList);
		}

		if (updateList.size() > 0) {
			rows = rows
					+ batchUpdateData(
							model,
							FundsSqlConstants.UPDATE_FUNDSSTATISTICS_MINUTE_SQL,
							updateList);
		}

		Long statisticsEnd = FrameUtil.getTime();
		Long times = statisticsEnd - statisticsBegin;
		logger.info("资金量统计（30分钟）本次运行数据开始时间："
				+ DateUtil.formatTimeToStr(beginTime,
						DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss)
				+ "结束时间："
				+ DateUtil.formatTimeToStr(overTime,
						DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss)
				+ "共运行记录数："
				+ rows
				+ "执行开始时间："
				+ DateUtil.formatTimeToStr(statisticsBegin,
						DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss)
				+ "执行结束时间:"
				+ DateUtil.formatTimeToStr(statisticsEnd,
						DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss) + "共花费时间："
				+ times);
	}

}
